var express = require('express');
var router = express.Router();
const player = require('../entity/player.js');
const fs = require('fs');
// const EventEmitter = require('events');
// //实现继承类
// class MyEmitter extends EventEmitter {}

// const myEmitter = new  MyEmitter();


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.post('/login', function(req, res) {
  console.log(req.body);
  let user = req.body.username;
  let nickname = req.body.nickname;
  let race = req.body.race;
  console.log(user, nickname, race);
  let newPlayer = {
    ...player
  };
  newPlayer.name = nickname;
  newPlayer.race = race;
  let userData = fs.readFileSync('./data/userData.json', 'utf8');
  if(userData){
    userData = JSON.parse(userData);
  }
  let hasUser = false;
  if(userData.users){
    for (let i = 0; i < userData.users.length; i++) {
      const element = userData.users[i];
      console.log(element);
      if(element.name === nickname){
        hasUser = true;
        // res.send({
        //   code:401,
        //   msg:'用户已存在'
        // })
        // return false;
      }
    }
  }
  //fs.writeFileSync('./data/player/, JSON.stringify(newPlayer));
  if(hasUser){
    res.send({
      code:401,
      msg:'用户已存在'
    })
  }else{
    userData.users.push(newPlayer);
    res.send({
      code:200,
      msg:'ok',
      data:{
        user: user,
        nickname: nickname,
        race: race
      }
    })
  }
});

module.exports = {router};
